// import dataService from '../services/DataService';
import moment from 'moment';
import config from '../../config';
// const COLOR_KECHUAN = '#3526F7';
// const COLOR_HUOCHUAN = '#21F55F';
// const COLOR_YOULUN = '#EF262E';
// const COLOR_TEZHONGCHUAN = '#92CCED';
// const COLOR_OTHERSHIP = '#A427EB';
// const COLOR_UNKNOWN = '#EDF55E';

// const SHIP_COLOR_REL = [
//   {color: COLOR_KECHUAN, typeArray: ['客货船', '客船', '客渡船']},
//   {color: COLOR_HUOCHUAN, typeArray: ['集装箱船', '散货船', '杂货船', '水产品运输船', '干货船']},
//   {color: COLOR_YOULUN, typeArray: ['油船', '散装化学品船/油船']},
//   {color: COLOR_TEZHONGCHUAN, typeArray: ['油污水处理船', '拖船', '工程船', '挖泥船', '工作船', '公务船']},
//   {color: COLOR_OTHERSHIP, typeArray: ['--']},
//   {color: COLOR_UNKNOWN, typeArray: ['散装化学品船', '液化气船', '水上平台']},
// ];

// 技能比武假数据整理
class DataGenerator {

  static getInstance() {
    if (!DataGenerator.instance) {
      DataGenerator.instance = new DataGenerator();
    }
    return DataGenerator.instance;
  }

  init() {
    this.locMap = {};
    this.infoMap = {};
    this.currentPart = [];
    this.nextPart = [];
    this.baseTime = 0;
    this.currentIndex = 0;
    this.currentPartIndex = 0;
    this.colorMap = {};

    config.SHIP_COLOR_ARRAY.forEach(row => {
      row.typeArray.forEach(type => {
        this.colorMap[type] = row.color;
      })
    });

    // 初始化时获取当前时间节点前3小时的所有船位数据
    // let ymd = moment().format('YYYY-MM-DD');
    // dataService.getAllLocation().then(locations => {
    //   if (window.dataLoaded) {
    //     window.dataLoaded('last');
    //   }
    //   locations.forEach(ary => {
    //     this.locMap[ary[0] + ''] = {
    //       terminalCode: ary[0] + '',
    //       secondsDiff: ary[1],
    //       latitude: ary[3],
    //       longitude: ary[2],
    //       course: ary[4],
    //       heading: ary[5],
    //       speed: ary[6]
    //     }
    //   })
    //   //console.log('loca:', this.locMap);
    // });

    // dataService.getShipInfo().then(ships => {
    //   console.log('thisp:::', typeof ships);
    //   ships.forEach(ary => {
    //     this.infoMap[ary[0] + ''] = {
    //       // terminalCode: ary[0],
    //       name: ary[1],
    //       typeName: ary[2]
    //     }
    //   })
    //   if (window.dataLoaded) {
    //     window.dataLoaded('ship');
    //   }
    // });

    this.getLocationPart(0);
// console.log('init', this, this.nextPart);
    // dataService.getLocationPart(1).then(res => {
    //   this.currentPart = res;
    // })

    // 读取第一块数据（一小时数据量比较大，分为10块，每次获取一块，直到结束）
  }


  getShipInfo(terminalCode) {
    let shipInfo = this.infoMap[terminalCode];
    if (shipInfo) {
      return {
        color: this.colorMap[shipInfo.typeName] || config.SHIP_COLOR_DEFAULT,
        shipName: shipInfo.name
      };
    }
    return {color:config.SHIP_COLOR_DEFAULT};
  }

  // 下载分块定位数据（一共10块）
  getLocationPart(idx) {
    if (this.downloading) {
      console.log('download already started for part:' + idx);
      return;
    }
    this.downloading = true;
    console.log('start downloading part data:' + idx);
    // dataService.getLocationPart(idx).then(res => {
    //   this.downloading = false;
    //   if (idx === 0) {
    //     if (window.dataLoaded) {
    //       window.dataLoaded('location');
    //     }
    //   }
    //   // console.log('part data downloaded.......' + idx);
    //   res.forEach(ary => {
    //     let obj = {
    //       secondsDiff: -1 * ary[0],
    //       terminalCode: ary[1],
    //       latitude: ary[3],
    //       longitude: ary[2],
    //       course: ary[4],
    //       heading: ary[5],
    //       speed: ary[6]
    //     };
    //     if (idx === 0) {
    //       this.currentPart.push(obj);
    //     } else {
    //       this.nextPart.push(obj)
    //     }
    //   })
    // })
  }

  startCountDown(baseTime) {
    this.baseTime = baseTime;
    this.timerHandler = setInterval(this.updateData.bind(this), 1000);
    // this.updateData()
  }

  updateData() {
    // console.log(this, this.nextPart);
    let secIndex = parseInt((new Date().getTime() - this.baseTime) / 1000, 10);
    if (secIndex > 3600) {
      clearInterval(this.timerHandler);
      // window.dataLoaded('finish');
      return;
    }
    let updCount = 0;
    let insCount = 0;
    if (this.currentPartIndex < 9 && this.nextPart.length === 0) {
      // console.log('get next part data.....', this.currentPartIndex + 1);
      this.getLocationPart(this.currentPartIndex + 1);
    }


    // console.log('updating::::', secIndex, this.currentIndex, this.currentPart);
    while (this.currentIndex < this.currentPart.length) {
      let dat = this.currentPart[this.currentIndex];
      if (-1 * dat.secondsDiff <= secIndex) {
        let loc = this.locMap[dat.terminalCode];
        if (!loc) {
          // console.log('add one ship:', dat);
          insCount++;
          // 船不存在，新增
          this.locMap[dat.terminalCode] = dat;
          // TODO: 船名等赋值
        } else {
          // console.log('update one data:', dat);
          updCount++;
          // 更新数据
          loc.secondsDiff = dat.secondsDiff;
          loc.latitude = dat.latitude;
          loc.longitude = dat.longitude;
          loc.course = dat.course;
          loc.heading = dat.heading;
          loc.speed = dat.speed;
          loc.aisTime = null;
        }
      } else {
        break;
      }
      this.currentIndex++;
    }
// let tmp = this.locMap['414072000'];
// tmp.latitude += 0.0001;
// tmp.longitude += 0.0001;
// tmp.aisTime = null;
//     console.log('sec:' + secIndex + ',new:' + insCount + ',upd:' + updCount + ',idx:' + this.currentIndex + ',all:' + this.currentPart.length);

    if (this.currentIndex >= this.currentPart.length) {
      // console.log('end of current part, change to next:::::::');
      this.currentPart = this.nextPart;
      this.nextPart = [];
      this.currentPartIndex++;
      this.currentIndex = 0;
    }
  }

  getShipLocationByRange(latLng0, latLng1, fromTimeStamp) {
// console.log(baseTime);
    return new Promise(resolve => {
      let result = [];
      Object.values(this.locMap).forEach(loc => {
        if (!loc.aisTime) {
          let timeStamp = this.baseTime - loc.secondsDiff * 1000;
          loc.aisTime = moment(timeStamp).format('YYYY-MM-DD HH:mm:ss');
          loc.timeStamp = timeStamp;
        }
        //console.log(loc, latLng0, latLng1, fromTimeStamp);
        if (loc.timeStamp > fromTimeStamp && loc.latitude > latLng0.lat && loc.latitude < latLng1.lat && loc.longitude > latLng0.lng && loc.longitude < latLng1.lng) {
          result.push(loc);
        }
      });
      // console.log('result::::', result);
      resolve(result);
    })

    // return result;
  }

  getShipLocationByMmsi(mmsi) {
    // console.log('search location', this.locMap);
    return new Promise(resolve => {
      resolve(this.locMap[mmsi]);
    })
  }
}

export default DataGenerator.getInstance();
